﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using UnityEngine;

namespace MrPP.ProgramPlatform {
 
    public class GzCompression {
   

        /// <summary>
        /// 压缩流
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static Stream Compress(Stream stream)
        {
        //sourceStream.Length
            MemoryStream responseStream = new MemoryStream();
            using (System.IO.Compression.GZipStream compressedStream = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Compress, true))
            {
                byte[] buffer = new byte[stream.Length];
                int checkCounter = stream.Read(buffer, 0, buffer.Length);
                if (checkCounter != buffer.Length) throw new ApplicationException();
                compressedStream.Write(buffer, 0, buffer.Length);
            }
            responseStream.Position = 0;
            return responseStream;
        }

        //解压数据
   
        static public Stream Decompress(Stream stream)
        {

            // 把 Stream 转换成 byte[]
            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            byte[] de = GzCompression.Decompress(data);

            return new MemoryStream(de);
      
        }

        /* */


        public static string Compress(string str)
        {
            //因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误 

            return Convert.ToBase64String(Compress(Encoding.Default.GetBytes(str)));
        }

        public static string Decompress(string str)
        {
            return Encoding.Default.GetString(Decompress(Convert.FromBase64String(str)));
        }
        static public byte[] Compress(byte[] data)
        {

            MemoryStream ms = new MemoryStream();
            GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress);
            zipStream.Write(data, 0, data.Length);
            zipStream.Flush();
            zipStream.Close();
            return ms.ToArray();

        }
        static public byte[] Decompress(byte[] data)
        {
            MemoryStream srcMs = new MemoryStream(data);
            GZipStream zipStream = new GZipStream(srcMs, CompressionMode.Decompress);
            MemoryStream ms = new MemoryStream();
            byte[] bytes = new byte[4096];
            int n;
            while ((n = zipStream.Read(bytes, 0, bytes.Length)) > 0)
            {
                ms.Write(bytes, 0, n);
            }
            zipStream.Close();
            return ms.ToArray();
        }

    }
}